<?php
namespace Tyrone\Consume;
use Tyrone\Lib\DatabasePool;
use Tyrone\Lib\SafeMedoo;
use Tyrone\Model\Game\Role;
use Tyrone\Model\Order;
use Tyrone\Model\PayCallback;
use Tyrone\Model\PlatServer;

class Pay extends Base
{
    protected $retry_times = 3;
    public function run($job,$mysql,$center_mysql,$retry_num=1){
        $resArr = json_decode($job,true);
        print_r($resArr);
        $data= $resArr["data"] ?? [];
        $order = $resArr["order"] ?? [];
        $uniqueKey = $order['order_id'];
        $this->actionLock($uniqueKey,function () use($job,$data,$mysql,$center_mysql,$retry_num) {
            $url = API_URL.'/inside/pay';
            goUrl($url,$data,function ($result) use($job,$mysql,$center_mysql,$retry_num,$url,$data){
                $resultArr = json_decode($result,true) ?:[];
                echo var_export(compact('url','data','result','retry_num'),true);
                if($resultArr['status']===true) return;
                if($retry_num < $this->retry_times){
                    $retry_num++;
                    $delay = min(30, 1 * pow(2, ($retry_num - 1)*3));
                    \Swoole\Coroutine::sleep($delay); // 协程睡眠
                    $this->run($job,$mysql,$center_mysql,$retry_num);
                }else{

                }

            });
        });
    }

    public function run_test($job,$mysql,$center_mysql){
        $resArr = json_decode($job,true);
        $pay = $resArr["pay"] ?? [];
        $uniqueKey = $pay['order_id'];
        $this->actionLock($uniqueKey,function () use($resArr,$mysql,$center_mysql){

            print_r($resArr);

            $order = $resArr["order"] ?? [];
            $serverData = $resArr["serverData"] ?? [];
            $playerInfo = $resArr["playerInfo"] ?? [];
            $url = $resArr["url"] ?? '';
            $platform = $resArr['platform'] ?? '';
            $master_platform = $resArr['master_platform'] ?? '';
            $plat_server = $resArr['plat_server'] ?? '';
            $OrderModel = new Order($center_mysql);
            $PayCallbackModel = new PayCallback($center_mysql);
            NewPHP2Erlang($url,$platform,$plat_server,BACKGROUND_RECHARGE, $serverData,function($resultArr) use ($playerInfo,$OrderModel,$PayCallbackModel,$pay,$order,$master_platform){

                $OrderModel->updateOrderStatus($order["order_id"], 2);
                $PayCallbackModel->updateCallbackStatus($pay["id"], 1);
                $PayCallbackModel->payLog($master_platform,$pay,$playerInfo);
                //返利
                goUrl('',function ($result){
                    //$pays["platform"], $pays["server_id"], $pays["player_id"], $pays["rmb"]
                });


            },function($resultArr) use($OrderModel,$order){
                $OrderModel->updateOrderStatus($order["order_id"], 0);
            });
        });

    }

    private function addPay($roleId, $chargeType = 1, $gold = 0, $rmb = 0, $payLogArr = []){

    }
}